﻿using INTEX.DataBase.Tools;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.Helpers;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.OracleClient;
using System.Windows;
using System.Data;
namespace WPFExcelReport
{

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class ITXTTF : DocumentBase
    {
        INTEX.DataBase.SETINTEXDB INTEXDB;
        ApplicationBase ApplicationBase;
        public OracleConnection OracleDB;
        public OracleCommand orlReadCommand = new OracleCommand();
        public IntexReptServBLClient proxy;
        private Dictionary<string, object> dicParamater;
        ITXPrint itxprint = new ITXPrint();
        public string sznop1 = "nop_front\r\n";
        public string sznop2 = "nop_middle\r\n";
        INTEXDBC INTEXDBC = null;
        Dictionary<string, string> env = new Dictionary<string, string>();
        List<string> watchpath = new List<string>();
        string printofile = "print";
        bool IsSetUp = false;
        public DataSet dsResult;

        public OracleCommand catCMD;
        public OracleDataAdapter myDa;
        public ITXTTF()
        {
            InitializeComponent();
            ReadConfig();
            Watcher watcher = new Watcher(watchpath, printofile);
        }
        public void SetUpOracle(Dictionary<string, object> dicSrcParamater)
        {
            string conn = "";
            conn = (string)dicSrcParamater["ConnectionString"];
            if (catCMD != null)
            {
                int pc = catCMD.Parameters.Count;
                for (int i = 0; i < pc; i++)
                {
                    catCMD.Parameters.RemoveAt(0);
                }
                if (catCMD.Connection.ConnectionString.Trim() == conn.Trim())
                {
                    if (catCMD.Connection.State == ConnectionState.Closed)
                    {
                        catCMD.Connection.Open();
                    }

                    return;
                }
            }
            catCMD = new OracleCommand();
            catCMD.CommandType = CommandType.Text;
            foreach (KeyValuePair<string, object> kvp in dicSrcParamater)
            {
                switch (kvp.Key)
                {
                    case "DBTYPE":
                        break;
                    case "AGENTID":
                        break;
                    case "CommandText":
                        catCMD.CommandText = (string)dicSrcParamater["CommandText"];
                        break;
                    case "ConnectionString":
                        conn = (string)dicSrcParamater["ConnectionString"];
                        if (catCMD.Connection == null)
                        {
                            catCMD.Connection = new OracleConnection(conn);
                        }
                        if (catCMD.Connection.State == ConnectionState.Closed)
                            catCMD.Connection.Open();
                        break;
                    case "CommandType":
                        break;
                    default:
                        break;
                }
            }
        }
        public DataSet GetDataSetByQuery(Dictionary<string, object> dicSrcParamater)
        {
            DataSet dsResult = new DataSet();
            try
            {
                string commandtype = "CommandText";
                string strCommandType;
                string dbType = "Oracle";
                if (dicSrcParamater.ContainsKey("DBTYPE"))
                {
                    dbType = dicSrcParamater["DBTYPE"].ToString();
                }
                SetUpOracle(dicSrcParamater);
                OracleParameter catCMDP;
                foreach (KeyValuePair<string, object> kvp in dicSrcParamater)
                {
                    switch (kvp.Key)
                    {
                        case "DBTYPE":
                        case "AGENTID":
                        case "ConnectionString":
                            break;
                        case "CommandType":
                            strCommandType = (string)dicSrcParamater["CommandType"];
                            switch (strCommandType)
                            {
                                case "StoredProcedure":
                                    catCMD.CommandType = CommandType.StoredProcedure;
                                    commandtype = "StoredProcedure";
                                    break;
                                case "TableDirect":
                                    catCMD.CommandType = CommandType.TableDirect;
                                    commandtype = "TableDirect";
                                    break;
                                default:
                                    catCMD.CommandType = CommandType.Text;
                                    break;
                            }
                            break;
                        case "CommandText":
                            catCMD.CommandText = (string)dicSrcParamater["CommandText"];
                            break;
                        default:
                            catCMDP = new OracleParameter();
                            catCMDP.ParameterName = kvp.Key;
                            catCMDP.Value = (string)kvp.Value;
                            catCMD.Parameters.Add(catCMDP);
                            break;
                    }
                }
                if (commandtype == "StoredProcedure")
                {
                    //Tracer.Verbose("Service", "StoredProcedure");
                    //MessageBox.Show("Dear Sir," + "StoredProcedure");
                    catCMD.ExecuteNonQuery();
                    return dsResult;
                }
                if (myDa == null)
                {
                    myDa = new OracleDataAdapter(catCMD);
                    myDa.ContinueUpdateOnError = true;
                }
                myDa.Fill(dsResult);

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return dsResult;
        }
        public DataSet Connect2Proxy(OracleCommand oracmd)
        {
            DataSet dsResult = new DataSet();
            Dictionary<string, object> dicQueryParamater;
            try
            {
                dicQueryParamater = new Dictionary<string, object>();
                dicQueryParamater.Clear();
                dicQueryParamater.Add("CommandText", oracmd.CommandText);
                dicQueryParamater.Add("CommandType", oracmd.CommandType.ToString());
                dicQueryParamater.Add("ConnectionString", oracmd.Connection.ConnectionString);
                foreach (OracleParameter cmp in oracmd.Parameters)
                {
                    dicQueryParamater.Add(cmp.ParameterName.ToString(), cmp.Value.ToString());
                }
                dsResult = GetDataSetByQuery(dicQueryParamater);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return dsResult;
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!IsSetUp)
                {
                    ApplicationBase = new ApplicationBase();
                    try
                    {
                        ApplicationBase.Load();
                    }
                    catch (Exception ex)
                    {
                        Tracer.Error(ex.StackTrace, ex);
                    }
                    dicParamater = ApplicationBase.dicParamater;
                }
                string strIntexSystem = (string)dicParamater["dbSystem"];
                string strUserName = (string)dicParamater["dbUser"];
                string strPassWord = (string)dicParamater["dbPwd"];
                string OracleDBConnString = "user id=" + strUserName
                 + ";data source=" + strIntexSystem
                 + ";password=" + strPassWord + ";Unicode=True;"
                    + "Persist Security Info=True;";
                if (OracleDB != null)
                {
                    OracleDB.Close();
                }
                OracleDB = new OracleConnection(OracleDBConnString);
                OracleDB.ConnectionString = OracleDBConnString;
                proxy = (IntexReptServBLClient)dicParamater["proxy"];
                /*
                INTEXDB = new INTEX.DataBase.SETINTEXDB();
                INTEXDBC = new INTEX.DataBase.Tools.INTEXDBC(OracleDB, proxy);
                DataRow dwData = INTEXDB.VKPOS.NewRow();
                dwData["VKPMANDANT"] = "00";
                dwData["VKPAUFKRS"] = "J3";
                dwData["VKPAUFLFD"] = "002006";
                OracleCommand   or1 = OracleDB.CreateCommand();
                DataSet result = new DataSet();
                or1.CommandText = "SELECT * FROM VKPOS WHERE VKPAUFKRS=:VKPAUFKRS AND VKPAUFLFD=:VKPAUFLFD";
                or1.Parameters.Add("VKPAUFKRS", OracleType.NVarChar).Value = dwData["VKPAUFKRS"].ToString();
                or1.Parameters.Add("VKPAUFLFD", OracleType.NVarChar).Value = dwData["VKPAUFLFD"].ToString();
                //DataSet SResult = Connect2Proxy(or1);
                //MessageBox.Show(SResult.Tables[0].Rows.Count.ToString());*/
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return;
        }
        public override void SetUp(Dictionary<string, object> dicParamater)
        {
            try
            {
                IsSetUp = true;
                using (new LongOperation(this, "读取符合条件的记录"))
                {
                    base.SetUp(dicParamater);
                    InitializeComponent();
                    this.dicParamater = dicParamater;
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public ITXTTF(StartupEventArgs e)
        {
            itxprint.szSaveFile = (string)e.Args[0];
            itxprint.printer = (string)e.Args[1];
            itxprint.copys = System.Convert.ToInt16(e.Args[2]);
            InitializeComponent();
            itxprint.Print();
        }
        private void ReadConfig()
        {
            string strKey = "";

            try
            {
                foreach (string key in System.Configuration.ConfigurationSettings.AppSettings)
                {
                    strKey = key.ToString();
                    if (strKey.StartsWith("wpath"))
                    {
                        watchpath.Add(ConfigurationSettings.AppSettings[strKey].ToString());
                    }
                    if (strKey.StartsWith("printofile"))
                    {
                        printofile = ConfigurationSettings.AppSettings[strKey].ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnFile_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string file = txtFile.Text.ToString();
                string printer = txtPrinter.Text.ToString();
                int ret;
                byte[] pbuf = new byte[128];
                System.Text.Encoding encAscII = System.Text.Encoding.ASCII;
                System.Text.Encoding encUnicode = System.Text.Encoding.Unicode;
                //ret = ITXTTFAPI.B_CreatePrn(10, @"\\192.168.1.156\TERM156");  
                ret = ITXTTFAPI.B_CreatePrn(0, file);// open file.   
                ITXTTFAPI.B_Set_DebugDialog(1);
                ITXTTFAPI.B_Set_Originpoint(0, 0);
                ITXTTFAPI.B_Select_Option(2);
                ITXTTFAPI.B_Set_Darkness(8);
                ITXTTFAPI.B_Del_Pcx("*");// delete all picture.
                ITXTTFAPI.B_WriteData(0, encAscII.GetBytes(sznop2), sznop2.Length);
                ITXTTFAPI.B_WriteData(1, encAscII.GetBytes(sznop1), sznop1.Length);
                //draw box.
                ITXTTFAPI.B_Draw_Box(20, 20, 4, 380, 280);
                //print text, true type text.
                ITXTTFAPI.B_Prn_Text(30, 40, 0, 2, 1, 1, 'N', "Article:");
                ITXTTFAPI.B_Prn_Text(180, 40, 0, 2, 1, 1, 'N', @"\06_\10_\17");
                ITXTTFAPI.B_Prn_Text(30, 80, 0, 2, 1, 1, 'N', "Length:");
                ITXTTFAPI.B_Prn_Text(180, 80, 0, 2, 1, 1, 'N', @"\CIy/\05m");
                ITXTTFAPI.B_Prn_Text(30, 120, 0, 2, 1, 1, 'N', @"Piece No.:\01");
                ITXTTFAPI.B_Prn_Barcode(30, 160, 0, "3", 2, 3, 40, 'B', @"\01");
                ITXTTFAPI.B_Bar2d_QR(30, 200, 1, 3, 'M', 'A', 0, 0, 0, @"\01");
                ITXTTFAPI.B_Print_Out(1);// copy 2. 
                ITXTTFAPI.B_ClosePrn();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace, ex.Message);
            }
        }

        private void btnPrinter_Click(object sender, RoutedEventArgs e)
        {
            string file = txtFile.Text.ToString();
            string printer = txtPrinter.Text.ToString();
            int ret;
            byte[] pbuf = new byte[128];
            System.Text.Encoding encAscII = System.Text.Encoding.ASCII;
            System.Text.Encoding encUnicode = System.Text.Encoding.Unicode;
            ret = ITXTTFAPI.B_CreatePrn(10, printer);
            //ret = ITXTTFAPI.B_CreatePrn(0, file);// open file.   
            ITXTTFAPI.B_Set_DebugDialog(1);
            ITXTTFAPI.B_Set_Originpoint(0, 0);
            ITXTTFAPI.B_Select_Option(2);
            ITXTTFAPI.B_Set_Darkness(8);
            ITXTTFAPI.B_Del_Pcx("*");// delete all picture.
            ITXTTFAPI.B_WriteData(0, encAscII.GetBytes(sznop2), sznop2.Length);
            ITXTTFAPI.B_WriteData(1, encAscII.GetBytes(sznop1), sznop1.Length);
            //draw box.
            ITXTTFAPI.B_Draw_Box(20, 20, 4, 380, 280);
            //print text, true type text.
            ITXTTFAPI.B_Prn_Text(30, 40, 0, 2, 1, 1, 'N', "Article:");
            ITXTTFAPI.B_Prn_Text(180, 40, 0, 2, 1, 1, 'N', @"\06_\10_\17");
            ITXTTFAPI.B_Prn_Text(30, 80, 0, 2, 1, 1, 'N', "Length:");
            ITXTTFAPI.B_Prn_Text(180, 80, 0, 2, 1, 1, 'N', @"\CIy/\05m");
            ITXTTFAPI.B_Prn_Text(30, 120, 0, 2, 1, 1, 'N', @"Piece No.:\01");
            ITXTTFAPI.B_Prn_Barcode(30, 160, 0, "3", 2, 3, 40, 'B', @"\01");
            ITXTTFAPI.B_Bar2d_QR(30, 200, 1, 3, 'M', 'A', 0, 0, 0, @"\01");
            ITXTTFAPI.B_Print_Out(1);// copy 2. 
            ITXTTFAPI.B_ClosePrn();
        }
        private void btnTranslate_Click(object sender, RoutedEventArgs e)
        {
            itxprint.szSaveFile = txtTFile.Text.ToString();
            itxprint.printer = txtPrinter.Text.ToString();
            itxprint.copys = System.Convert.ToInt16(txtCopy.Text.ToString());
            //itxprint.Print();
            itxprint.CreateTransFile();
        }
    }
}
